package com.futao.niudong.controller;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.UUID;

/**
 * @author futao@gmail.com
 * @date 2022/3/10
 */
@Slf4j
@RestController
@RequestMapping("/es")
public class EsController {

    public static final String LDK_INDEX = "ldk_index";
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 保存案例
     */
    @PostMapping("/document")
    public void saveDocument() {
        UserObject userObject = new UserObject(UUID.randomUUID().toString(), "李达康", 18, true, new String[]{"抽烟", "喝酒", "烫头"});
        // 索引名称
        IndexRequest indexRequest = new IndexRequest(LDK_INDEX);
        // 指定id
        indexRequest.id(userObject.id);
        // 存储的document内容
        indexRequest.source(JSON.toJSONString(userObject), XContentType.JSON);
        try {
            IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            log.info("{}", JSON.toJSONString(indexResponse, true));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/document/{id}")
    public String queryById(@PathVariable String id) {
        GetRequest getRequest = new GetRequest(LDK_INDEX, id);
        // 不获取source，即不加载document数据
        // getRequest.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);
        // 禁用提取存储字段
        // getRequest.storedFields("_none_");
        try {
            GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            // if (documentFields.isExists()) {
            //     return documentFields.getSourceAsString();
            // }
            return JSON.toJSONString(documentFields, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "nnn";
    }

    @DeleteMapping("/document/{id}")
    public String deleteById(@PathVariable String id) {
        try {
            DeleteResponse delete = restHighLevelClient.delete(new DeleteRequest(LDK_INDEX, id), RequestOptions.DEFAULT);
            return JSON.toJSONString(delete, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @PutMapping("/document/{id}")
    public String update(@PathVariable String id) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(LDK_INDEX, id);
        UserObject userObject = new UserObject(UUID.randomUUID().toString(), "李达康2", 180, true, new String[]{"抽1烟", "喝2酒", "烫3头"});
        updateRequest.doc(JSON.toJSONString(userObject), XContentType.JSON);
        return JSON.toJSONString(restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT), true);
    }

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    public static class UserObject {
        private String id;
        private String username;
        private int age;
        private boolean isMember;
        private String[] hobbies;
    }
}
